package com.suke.czx.modules.wx.handler;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.suke.czx.modules.wx.builder.TextBuilder;
import com.suke.czx.modules.wx.config.WxPayProperties;
import com.suke.czx.modules.wxadmin.entity.DkUserEntity;
import com.suke.czx.modules.wxadmin.entity.DkUserInvEntity;
import com.suke.czx.modules.wxadmin.service.DkUserInvService;
import com.suke.czx.modules.wxadmin.service.DkUserService;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class ScanHandler extends AbstractHandler {
	@Autowired
	private WxPayProperties wxPayProperties;

	@Autowired
	private DkUserService dkUserService;
	
	@Autowired
	private DkUserInvService dkUserInvService;

	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage, Map<String, Object> map, WxMpService wxMpService,
			WxSessionManager wxSessionManager) throws WxErrorException {
		
		// 获取微信用户基本信息
		try {
			WxMpUser userWxInfo = wxMpService.getUserService().userInfo(wxMpXmlMessage.getFromUser(), null);
			if (userWxInfo != null) {
				// TODO 可以添加关注用户到本地数据库
			}
		
		String content = "【210天诗词精读学习计划】火热报名中!\r\n\r\n" + "🎁全勤学习，返129元现金\r\n"
				+ "🌹奖励不断：每学习45天，免费领取精品正版图书一套，共计4套\r\n\r\n" + "<a href='http://" + wxPayProperties.getHost()
				+ "/x_springboot/wx/redirect/" + wxPayProperties.getAppId() + "?url=http://" + wxPayProperties.getHost()
				+ "/x_springboot/wx/base/" + wxPayProperties.getAppId() + "/rout?p=pay_1_1&isshow=1'>☞戳我报名，古诗不用背！</a>"
				+ "\r\n" + "<a href='http://" + wxPayProperties.getHost() + "/x_springboot/wx/redirect/"
				+ wxPayProperties.getAppId() + "?url=http://" + wxPayProperties.getHost() + "/x_springboot/wx/base/"
				+ wxPayProperties.getAppId() + "/rout?p=pay_1_1&isshow=1'>☞戳我报名，听完自然会!</a>" + "\r\n\r\n"
				+ "已报名？点击下方「今日阅读」进行第一天学习！\r\n" + " ↓  ↓  ↓";
		//判断是否是自己扫码
		String inv_user_openid = wxMpXmlMessage.getEventKey().replace("qrscene_", "");
		this.logger.info("扫码事件OPENID: " + wxMpXmlMessage.getFromUser() + "来源：" + inv_user_openid);
		if(!wxMpXmlMessage.getFromUser().equals(inv_user_openid)){
			new Thread(new Runnable() {
				public void run() {
					//处理事件的二维码通知 对应的客户
					String c = "亲爱的，您的好友"+userWxInfo.getNickname()+"扫您分享的二维码关注了诗词精读，如果Ta成功报名（在扫别人的二维码之前），您将获得0.5个领书币。领书币既可以单独领书，也可以用于补卡（详情见个人中心）。\r\n\r\n"
							+ "请平时多分享朋友圈，多与好友沟通，尽量多点储备领书币。";
					WxMpKefuMessage message = WxMpKefuMessage.TEXT().toUser(inv_user_openid).content(c).build();
					try {
						wxMpService.getKefuService().sendKefuMessage(message);
					} catch (WxErrorException e) {
						e.printStackTrace();
					}
					//处理更新邀请记录
					DkUserInvEntity user_inv = dkUserInvService.queryObject(wxMpXmlMessage.getFromUser());	
					if(user_inv==null){
						user_inv = new DkUserInvEntity();
						user_inv.setUserId(wxMpXmlMessage.getFromUser());
						user_inv.setInvUserId(inv_user_openid);
						user_inv.setUpdateTime(new Date());
						dkUserInvService.save(user_inv);
						
					}else{
						user_inv.setInvUserId(inv_user_openid);
						user_inv.setUpdateTime(new Date());
						dkUserInvService.update(user_inv);
					}
				}
			}).start();
		}
		
		
			return new TextBuilder().build(content, wxMpXmlMessage, wxMpService);
		} catch (Exception e) {
			this.logger.error(e.getMessage(), e);
		}

		return null;
	}
}
